//lcd8.c

#include <AT89X52.H>
#include "lcd8.h"

#define FUNCTION    0x38
#define CONTROL     0x0c
#define CLRSCR      0x01
#define RETHOME     0x03
#define ENTRYMODE   0x06
#define PortData    P0
#define BG          P1_7
#define RS          P1_0
#define RW          P1_1
#define EN          P1_2

void Delay(unsigned int n)
{
    unsigned int j;
    for(j=0;j<n;j++);
}

void SetupLcd(void)
{
    Delay(150);
    WriteCmd(0x30);
    Delay(150);
    WriteCmd(0x30);
    Delay(150);
    WriteCmd(0x30);
    Delay(150);

    EN = 1;
    Delay(0);
    EN = 0;
    WaitBusy();
    WriteCmd(FUNCTION);
    WriteCmd(CONTROL);
    WriteCmd(CLRSCR);
    WriteCmd(ENTRYMODE);
}

void WriteCmd(unsigned char byte)
{
    WaitBusy();
    RS = 0;
    RW = 0;
    Delay(0);
    PortData = byte;
    EN = 1;
    Delay(0);
    EN = 0;
}

void WriteChar(unsigned char ch)
{
    WaitBusy();
    RS = 1;
    RW = 0;
    Delay(0);
    PortData = ch;
    EN = 1;
    Delay(0);
    EN = 0;
}

void WriteStr(unsigned char *str)
{
	while(*str)
		WriteChar(*str++);
}

void WriteNum(unsigned char num)
{
    unsigned char digit;
    digit = num/100;
    WriteChar(digit + '0');           //write tram
    digit = num/10;
    digit = digit % 10;
    WriteChar(digit + '0');           //write chuc
    digit = num % 100;
    digit = digit % 10;
    WriteChar(digit + '0');           //write dvi
}



void WriteNible(unsigned char byte)
{
    if(byte < 10)
    {
        byte = byte + 48;
        WriteChar(byte);
    }
    else
    {
        byte= byte + 55;
        WriteChar(byte);
    }
}

void WriteHex(unsigned char byte)
{
    unsigned char tbyte;
    tbyte = (byte & 0xf0) >> 4;
    WriteNible(tbyte);                       //hi  nible
    tbyte = byte & 0x0f;
    WriteNible(tbyte);                       //low nible
}

void GoHome()
{
    WriteCmd(RETHOME);
    Delay(100);
}

void GoToXY(unsigned char row,unsigned char col)
{
    unsigned char ac;
    ac = 0x80;
    ac = ac | ((row & 1) << 6);
    ac = ac | (col & 15);
    WriteCmd(ac);
}

void ClearScreen(void)
{
    WriteCmd(CLRSCR);
    Delay(100);
}

void WaitBusy(void)
{
    char i,nLcdBusy;
    PortData = (PortData | 0x80);
    RS = 0;
    RW = 1;
    for(i=0;i<50;i++)
    {
        while(1)
        {
            EN = 1;
            Delay(0);
            nLcdBusy = (PortData & 0x80);
            EN = 0;
            Delay(0);
            if(nLcdBusy == 0)
                break;
        }
    }
}

void SetBgOn(void)
{
    BG = 1;
}

void SetBgOff(void)
{
    BG = 0;
}